package com.jiaai.util;

import com.jiaai.util.spread_db_util.DBHisUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * class_name:DateTools
 * describe:------------------>日期处理类
 * create_user:张昉平
 * create_date:2018/2/27
 * create_time:12:09
 */
public class DateTools {

    private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

    private static final SimpleDateFormat YEAR_FORMATTER = new SimpleDateFormat("yyyy");

    private static final SimpleDateFormat YEAR_MONTH_FORMATTER = new SimpleDateFormat("yyyy-MM");

    /**
     * 获取两个日期内的相隔, 年月列表 2018-01, 2018-02 .etc
     * @param oldDate yyyy-MM-dd HH:mm:ss格式
     * @param newDate
     * @return
     */
    public static List<String> yearMonthsBetween(String oldDate, Date newDate){
        List<String> list = DBHisUtil.getYMBetween(strToDate(oldDate), newDate);
        return list;
    }
    public static List<String> yearMonthsBetween(String oldDate, String newDate){
        List<String> list = DBHisUtil.getYMBetween(strToDate(oldDate), strToDate(newDate));
        return list;
    }


    public static List<String> yearBetween(String oldDate, Date newDate){
        String oldYear = YEAR_FORMATTER.format(strToDate(oldDate));
        String newYear = YEAR_FORMATTER.format(newDate);

        int oldYearInt = Integer.parseInt(oldYear);
        int newYearInt = Integer.parseInt(newYear);

        List<String> years = new ArrayList<String>();

        for (int i = 0; i <= (newYearInt - oldYearInt); i++){
            years.add(oldYearInt + i + "");
        }
        return years;
    }

    /**
     * 日期转星期
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    public static Date strToDate(String str){
        try {
            return new SimpleDateFormat(DATE_PATTERN).parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getThisYearMonth(){
        return YEAR_MONTH_FORMATTER.format(new Date());
    }

    public static void main(String[] args) {
        System.out.println(yearMonthsBetween("2018-01-01 00:00:00", new Date()));
        System.out.println(yearBetween("2018-01-01 00:00:00", new Date()));
    }

}
